﻿using System;
using System.IO;
using System.Timers;

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
public class Logger
{
    private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
    private static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
    private static readonly Timer cleanupTimer;
    private const int MAX_DAYS = 7;
    private const string LOG_BASE_PATH = "Log";

    static Logger()
    {
        try
        {
            // 创建一个每天执行一次的定时器
            cleanupTimer = new Timer(24 * 60 * 60 * 1000); // 24小时
            cleanupTimer.Elapsed += CleanupOldLogs;
            cleanupTimer.Start();

            // 启动时执行一次清理
            CleanupOldLogs(null, null);
        }
        catch (Exception ex)
        {
            WriteError("Failed to initialize logger cleanup timer", ex);
        }
    }

    public static void WriteInfo(string info)
    {
        if (loginfo.IsInfoEnabled)
        {
            loginfo.Info(info);
        }
    }



    public static void WriteError(string error)
    {
        if (logerror.IsErrorEnabled)
        {
            logerror.Error(error);
        }
    }

    public static void WriteError(string info, Exception ex)
    {
        if (logerror.IsErrorEnabled)
        {
            logerror.Error(info, ex);
        }
    }

    private static void CleanupOldLogs(object sender, ElapsedEventArgs e)
    {
        try
        {
            if (!Directory.Exists(LOG_BASE_PATH))
                return;

            string[] logTypes = { "LogError", "LogInfo", "LogMqtt" };
            DateTime cutoffDate = DateTime.Now.AddDays(-MAX_DAYS);

            foreach (string logType in logTypes)
            {
                string logTypeDir = Path.Combine(LOG_BASE_PATH, logType);
                if (!Directory.Exists(logTypeDir))
                    continue;

                // 获取所有日期文件夹
                string[] dateDirs = Directory.GetDirectories(logTypeDir);
                foreach (string dateDir in dateDirs)
                {
                    string dirName = Path.GetFileName(dateDir);
                    if (DateTime.TryParseExact(dirName, "yyyyMMdd", null,
                        System.Globalization.DateTimeStyles.None, out DateTime dirDate))
                    {
                        if (dirDate < cutoffDate)
                        {
                            try
                            {
                                Directory.Delete(dateDir, true);
                                WriteInfo($"Deleted old log directory: {dateDir}");
                            }
                            catch (Exception ex)
                            {
                                WriteError($"Failed to delete log directory: {dateDir}", ex);
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            WriteError("Error during log cleanup", ex);
        }
    }

    // 提供手动清理方法
    public static void ForceCleanupOldLogs()
    {
        CleanupOldLogs(null, null);
    }

    // 在应用程序退出时调用此方法
    public static void Shutdown()
    {
        if (cleanupTimer != null)
        {
            cleanupTimer.Stop();
            cleanupTimer.Dispose();
        }
    }
}